<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserRequest;
use App\Models\Image;
use App\Models\User;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;


class UserController extends Controller
{
    /*接口参数说明
     * name password verify_key(短信验证码接口返回的key) verify_code 短信验证码
     */

    //用户注册接口
    public function store(UserRequest $request)
    {
        $data = \Cache::get($request->verify_key);
        //缓存超时
        if (!$data) {
            return $this->response->error('验证码已失效', 422);
        }
        if (!hash_equals($data['code'], $request->verify_code)) {
            //返回401状态码
            return $this->response->errorUnauthorized('验证码无效');
        }
        $phone = $data['phone'];
        $user = new \App\Models\User();
        $user->name = $request->name;
        $user->password = bcrypt($request->password);
        $user->phone = $phone;
        $user->save();
        \Cache::forget($request->verify_key);
        return $this->response->item($user, new UserTransformer())->setMeta([
            'access_token' => \Auth::guard('api')->fromUser($user),
            'token_type' => 'Bearer',
            'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
        ]);
        // return $this->response->created();
    }

    public function me()
    {
        return $this->response->item($this->user(), new UserTransformer());
    }

    //用户资料编辑
    public function update(Request $request)
    {
        //获取当前用户
        $user = \Auth::guard('api')->user();
        //获取传递过来的参数
        $userInfo = $request->only(['name', 'email', 'avatar_image_id']);
        //查找图片id,如果存在则把路径存入用户的表的avatar字段中
        if ($request->avatar_image_id) {
            $image = Image::find($request->avatar_image_id);
            $userInfo['avatar'] = $image['path'];
        }
        $user->update($userInfo);

        return $this->response->item($user, new UserTransformer());

    }
}
